package com.xs.ai.services;

import com.fasterxml.jackson.databind.JsonNode;
import com.xs.ai.dto.UserPreferences;
import com.xs.ai.entity.Email;
import com.xs.ai.entity.User;
import com.xs.ai.entity.UserDecision;
import org.springframework.stereotype.Service;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class UserBehaviorLearningService {
    
    private final UserDecisionRepository decisionRepository;
    private final EmailRepository emailRepository;
    private final ContactImportanceRepository contactRepository;
    
    /**
     * 学习用户的邮件优先级偏好
     */
    public void learnEmailPriorityPreferences(Long userId) {
        // 获取最近100个决策记录
        List<UserDecision> recentDecisions = decisionRepository
            .findRecentByUserAndType(userId, "email_priority", 100);
        
        Map<String, PriorityPattern> patterns = new HashMap<>();
        
        for (UserDecision decision : recentDecisions) {
            String senderEmail = decision.getContextData().get("sender_email");
            String aiSuggestion = decision.getAiSuggestion();
            String userChoice = decision.getUserChoice();
            
            // 如果用户经常修改AI建议
            if (!aiSuggestion.equals(userChoice)) {
                PriorityPattern pattern = patterns.computeIfAbsent(
                    senderEmail, k -> new PriorityPattern()
                );
                pattern.addOverride(aiSuggestion, userChoice);
            }
        }
        
        // 更新联系人重要性评分
        for (Map.Entry<String, PriorityPattern> entry : patterns.entrySet()) {
            updateContactImportance(userId, entry.getKey(), entry.getValue());
        }
    }
    
    /**
     * 学习用户的回复风格
     */
    public String getUserReplyStyle(Long userId) {
        // 分析用户最近发送的邮件
        List<Email> sentEmails = emailRepository
            .findRecentSentByUser(userId, 50);
        
        StringBuilder styleAnalysis = new StringBuilder();
        styleAnalysis.append("用户回复风格特征:\n");
        
        // 1. 平均回复长度
        int avgLength = sentEmails.stream()
            .mapToInt(e -> e.getBodyText().length())
            .sum() / sentEmails.size();
        styleAnalysis.append(String.format("- 平均回复长度: %d字符 (%s)\n", 
            avgLength, avgLength < 200 ? "简洁" : "详细"));
        
        // 2. 常用开场白
        Map<String, Long> openings = sentEmails.stream()
            .map(e -> extractOpening(e.getBodyText()))
            .filter(Objects::nonNull)
            .collect(Collectors.groupingBy(s -> s, Collectors.counting()));
        
        styleAnalysis.append("- 常用开场白: ");
        styleAnalysis.append(openings.entrySet().stream()
            .sorted(Map.Entry.<String, Long>comparingByValue().reversed())
            .limit(3)
            .map(Map.Entry::getKey)
            .collect(Collectors.joining(", ")));
        styleAnalysis.append("\n");
        
        // 3. 语气分析
        boolean usesFormalLanguage = sentEmails.stream()
            .anyMatch(e -> containsFormalPhrases(e.getBodyText()));
        styleAnalysis.append(String.format("- 语气: %s\n", 
            usesFormalLanguage ? "正式专业" : "友好随和"));
        
        // 4. 是否使用emoji
        boolean usesEmoji = sentEmails.stream()
            .anyMatch(e -> containsEmoji(e.getBodyText()));
        styleAnalysis.append(String.format("- 使用emoji: %s\n", 
            usesEmoji ? "是" : "否"));
        
        return styleAnalysis.toString();
    }
    
    /**
     * 获取用户偏好设置
     */
    public UserPreferences getUserPreferences(Long userId) {
        User user = userRepository.findById(userId).orElseThrow();
        
        UserPreferences prefs = new UserPreferences();
        
        // 从AI配置中读取
        Map<String, Object> aiPrefs = user.getAiPreferences();
        prefs.setPriorityAreas((List<String>) aiPrefs.get("priority_areas"));
        prefs.setWorkingHours((String) aiPrefs.get("working_hours"));
        prefs.setDelegationStyle((String) aiPrefs.get("delegation_style"));
        
        return prefs;
    }
    
    /**
     * 记录用户决策用于学习
     */
    public void recordDecision(Long userId, String decisionType, 
                              String contextType, Object contextData,
                              String aiSuggestion, String userChoice) {
        UserDecision decision = new UserDecision();
        decision.setUserId(userId);
        decision.setDecisionType(decisionType);
        decision.setContextType(contextType);
        decision.setContextData(objectMapper.convertValue(contextData, JsonNode.class));
        decision.setAiSuggestion(aiSuggestion);
        decision.setUserChoice(userChoice);
        decision.setMatched(aiSuggestion.equals(userChoice));
        
        decisionRepository.save(decision);
        
        // 如果积累了足够的决策记录，触发学习
        long decisionCount = decisionRepository.countByUserAndType(userId, decisionType);
        if (decisionCount % 50 == 0) {
            // 异步触发学习过程
            CompletableFuture.runAsync(() -> retrainUserModel(userId, decisionType));
        }
    }
    
    private void retrainUserModel(Long userId, String decisionType) {
        log.info("开始重新训练用户模型: userId={}, type={}", userId, decisionType);
        
        switch (decisionType) {
            case "email_priority":
                learnEmailPriorityPreferences(userId);
                break;
            case "meeting_response":
                learnMeetingPreferences(userId);
                break;
            // 其他学习类型...
        }
        
        log.info("用户模型训练完成");
    }
}